//
//  iAutoProxyAppDelegate.m
//  iAutoProxy
//
//  Created by Yingxin Wu on 11-10-15.
//  Copyright 2011年 XinThink. All rights reserved.
//

#import "iAutoProxyAppDelegate.h"

@implementation iAutoProxyAppDelegate

@synthesize window;
@synthesize hostTextField;
@synthesize portTextField;
@synthesize usernameTextField;
@synthesize passwordTextField;
@synthesize localPortTextField;
@synthesize localAddressTextField;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [self load];
}

- (IBAction)connect:(id)sender {
    NSLog(@"sent connect, saving settings");
    [self save];
}

- (IBAction)disconnect:(id)sender {
    NSLog(@"sent disconnect");
}

/*
 * Load ssh account from file (within $HOME directory)
 */
- (void)load {
    NSString *file = [@"~/.iAutoProxy/ssh_account.xml" stringByExpandingTildeInPath];
    if (![[NSFileManager defaultManager] fileExistsAtPath:file]) {
        NSLog(@"account file NOT found, left it empty");
        return;
    }
    
    // load from file
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:file];
    
    // update views
    self.hostTextField.stringValue = [dict valueForKey:@"host"];
    self.portTextField.stringValue = [dict valueForKey:@"port"];
    self.usernameTextField.stringValue = [dict valueForKey:@"username"];
    self.passwordTextField.stringValue = [dict valueForKey:@"password"];
    self.localAddressTextField.stringValue = [dict valueForKey:@"localAddress"];
    self.localPortTextField.stringValue = [dict valueForKey:@"localPort"];
}

/*
 * Save ssh account to file (within $HOME directory)
 */
- (void)save {
    NSString *baseDir = [@"~/.iAutoProxy" stringByExpandingTildeInPath];
    NSString *file = [baseDir stringByAppendingString:@"/ssh_account.xml"];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL dirExists = [fileMgr fileExistsAtPath:baseDir];
    
    if (!dirExists) {
        NSError *errors = [[NSError alloc] init];
        BOOL created = [fileMgr createDirectoryAtPath:baseDir withIntermediateDirectories:YES attributes:nil error:&errors];

        NSLog(@"mkdir %@ success? %d, errors:%@", baseDir, created, errors);
        [errors release];
    }
    
    // store ssh account in a dictionary, and write to a file
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:5];
    [dict setValue:self.hostTextField.stringValue forKey:@"host"];
    [dict setValue:self.portTextField.stringValue forKey:@"port"];
    [dict setValue:self.usernameTextField.stringValue forKey:@"username"];
    [dict setValue:self.passwordTextField.stringValue forKey:@"password"];
    [dict setValue:self.localAddressTextField.stringValue forKey:@"localAddress"];
    [dict setValue:self.localPortTextField.stringValue forKey:@"localPort"];
    
    [dict writeToFile:file atomically:YES];
    [dict release];
}
@end
